package com.ddsso.auth.web.util;

import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class servletUtil {

	/**
	 * json请求服务端
	 * @param rqurl
	 * @param rqjson
	 */
    public static  String   requestJson(String rqurl,JSONObject rqjson){
    	
    	
    	
    	String result="";
    	
    	BufferedReader reader=null;
    	HttpURLConnection connection=null;
    	try{
            //创建连接
            URL url = new URL(rqurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            
            connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");       
            
            connection.connect();

            //POST请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            //JSONObject obj = new JSONObject(rqjson);

            //out.writeBytes(rqjson.toString());//这个中文会乱码
            out.write(rqjson.toString().getBytes());//这样可以处理中文乱码问题
            out.flush();
            out.close();

            //读取响应
            reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes());
                sb.append(lines);
            }
            // System.out.println("接收到的json:"+sb);
            result=sb.toString();
           
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
        	if (reader!=null) {
        		 try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
        	if (connection!=null) {
        		// 断开连接
                connection.disconnect();
			}
        }
    	return result;
    	
    }
    
    
    
    
    
    
   
}
